<template>
  <!-- 放置弹层组件 -->
  <!-- @open="getUserSimpleList" 第一种 在@open中调用接口 -->
  <el-dialog
    :title="showTitle"
    :visible="showDialog"
    :close-on-click-modal="false"
    @close="closeDialog"
    @open="getUserSimpleList"
  >
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      ref="refForm"
      label-width="120px"
      :model="form"
      :rules="rules"
    >
      <el-form-item
        label="部门名称"
        prop="name"
      >
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-10个字符"
        />
      </el-form-item>
      <el-form-item
        label="部门编码"
        prop="code"
      >
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-10个字符"
        />
      </el-form-item>
      <el-form-item
        label="部门负责人"
        prop="manager"
      >
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="部门介绍"
        prop="introduce"
      >
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button
        type="primary"
        size="small"
        @click="confirmAddDepts"
      >确定</el-button>
      <!-- 给取消添加点击事件 -->
      <el-button
        size="small"
        @click="closeDialog"
      >取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getUserSimpleListApi,
  addDepartmentApi,
  getDepartmentDetailApi,
  editDepartmentApi
} from '@/api/departments'
export default {
  name: 'AddDepts',
  // 需要传入一个props变量来控制 显示或者隐藏
  props: {
    // 父传子的显示隐藏框
    showDialog: {
      type: Boolean,
      default: false
    },
    // 获取树状图data
    nodeData: {
      type: Object,
      default: () => {}
    },
    // 接收平铺的数据列表
    departList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不可为空', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '部门名称长度为1-10个字符',
            trigger: 'blur'
          },
          // 自定义校验添加子名字是否重复
          { validator: this.validateDeptsName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不可为空', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '部门编码长度为1-10个字符',
            trigger: 'blur'
          },
          // 自定义校验添加部门编码是否重复
          { validator: this.validateDeptsCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不可为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不可为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍长度为1-300个字符',
            trigger: 'blur'
          }
        ]
      },
      userList: []
      // 弹层的标题
      // showTitle: ''
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑部门' : '添加部门'
    }
  },
  methods: {
    // 获取部门详情
    async getDepartmentDetail() {
      const { data } = await getDepartmentDetailApi(this.nodeData.id)
      // 把data绑定给表单
      this.form = data
    },
    closeDialog() {
      // this.showDialog = false
      // 重新渲染
      this.$emit('update:showDialog', false)
      // 清空绑定在表单域上的数据和校验
      this.$refs.refForm.resetFields()
      // this.$emit('closeDialogFn')
      this.form = { code: '', introduce: '', manager: '', name: '', pid: '' }
    },
    /**
     * 校验部门名称是否重复
     */
    validateDeptsName(rule, value, callback) {
      if (value === this.nodeData.name) {
        callback()
        return
      }
      let arr = []
      // 判断数组中有一项符合条件就返回true
      if (this.form.id) {
        arr = this.departList.filter((item) => item.pid === this.nodeData.pid)
      } else {
        arr = this.nodeData.children
      }
      const result = arr.some((item) => item.name === value)
      //  如果是true验证不通过，callback new error ，false则直接callback
      result ? callback(new Error('部门名称不可重复')) : callback()
    },
    /**
     * 校验部门编码
     */
    validateDeptsCode(rule, value, callback) {
      if (this.form.id && value === this.nodeData.code) {
        callback()
        return
      }
      const result = this.departList.some((item) => item.code === value)
      result ? callback(new Error('部门编码不可重复')) : callback()
    },
    /**
     * 获取部门负责人列表
     */
    async getUserSimpleList() {
      const { data } = await getUserSimpleListApi()
      this.userList = data
    },
    /**
     * 确定添加部门数据
     */
    confirmAddDepts() {
      this.$refs.refForm.validate(async(valid) => {
        if (!valid) return
        // 说明校验通过了
        if (this.form.id) {
          await editDepartmentApi(this.form)
          this.$message.success('恭喜！部门修改成功')
        } else {
          this.form.pid = this.nodeData.id
          await addDepartmentApi(this.form)
          this.$message.success('恭喜！部门添加成功')
        }
        // 添加成功后 成功提示+ 重新获取列表 + 弹框关闭（重置表单）
        this.closeDialog()
        // 子传父重新获取表单数据
        this.$emit('add-success')
      })
    }
  }
}
</script>
